package cn.tedu.spring;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

/**
 * Author：程Sir
 * Name： framework
 * Content:
 */
@Configuration
@Component
@MapperScan("cn.tedu.spring.mapper") // 因为现在持久层的映射由xml配置文件完成，扫描动作被namespace替代，则不需要配置MapperScan
@PropertySource("classpath:db.properties")
public class SpringConfig {

    @Bean
    public DruidDataSource druidDataSource(
            @Value("${jdbc.url}") String url,
            @Value("${db.username}")String username,
            @Value("${db.password}")String password,
            @Value("${db.maxActive}")Integer MaxActive,
            @Value("${db.initialSize}")Integer initialSize
    ){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setMaxActive(MaxActive);
        dataSource.setInitialSize(initialSize);
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(
            DruidDataSource druidDataSource,
            @Value("${mybatis.mapper.locations}")Resource[] resource){
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(druidDataSource);
        sessionFactoryBean.setMapperLocations(resource);
        return sessionFactoryBean;
    }

}
